<template>
  <div class="content">
    <el-form :inline="true" :model="formInline">
      <el-form-item label="工种类别">
        <workTypeSelect v-model="formInline.workTypeId"></workTypeSelect>
      </el-form-item>
      <el-form-item label="发布时间">
        <datePickerRange v-model:start="formInline.startTime" v-model:end="formInline.endTime" type="datetimerange"></datePickerRange>
      </el-form-item>
      <el-form-item label="审核状态">
        <el-select v-model="formInline.status" placeholder="请选择审核状态">
          <el-option :label="item.name" :value="item.value" v-for="item in auditStateList" :key="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button type="primary" @click="dialogVisible=true" plain>新增订单</el-button>
        <el-button type="danger" @click="orderDel" plain :disabled='ids.length==0'>批量删除</el-button>
        <el-button @click="init">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData.records" :stripe="true" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column type="index" fixed="left" />
      <el-table-column prop="workTypeName" label="工种类型" align="center" min-width="150" fixed="left" />
      <el-table-column prop="address" label="工作地点" align="center" min-width="300">
        <template #default="scope">
          {{scope.row.areaName}}{{scope.row.address}}
        </template>
      </el-table-column>
      <el-table-column label="招工需求" align="center" min-width="400">
        <template #default="scope">
          {{proxy.$utils.truncateString(scope.row.requirement?scope.row.requirement:scope.row.title,100)}}
          <el-button type="primary" text @click="seeDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" align="center" min-width="150" prop="phone" />
      <el-table-column prop="realName" label="联系人" align="center" min-width="150" />
      <el-table-column label="订单状态" align="center" min-width="100">
        <template #default="scope">
          <el-tag v-if="[0,1].includes(scope.row.status)">{{auditState_format(scope.row.status)}}</el-tag>
          <el-tag :type="tag_type(scope.row.status)" v-else>{{auditState_format(scope.row.status)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="oneDayWage" label="价格" align="center" />
      <!-- <el-table-column prop="workNumDictName" label="用工人数" align="center" />
      <el-table-column prop="constructionPeriodDictName" label="预计工期" align="center" /> -->
      <el-table-column prop="auditTime" label="指派时间" align="center" min-width="180">
        <template #default="scope">
          {{proxy.$utils.dateTimeFormateFn(scope.row.gmtModified,"all")}}
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" min-width="180">
        <template #default="scope">
          {{proxy.$utils.dateTimeFormateFn(scope.row.gmtCreate,"all")}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="200">
        <template #default="scope">
          <el-button type="primary" text @click="handleClick(scope.row,1)" :disabled="disabledStatus(scope.row.status)">指派订单</el-button>
          <el-button type="primary" text @click="handleClick(scope.row,2)" :disabled="disabledStatus(scope.row.status)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-if="tableData['total']" :total="tableData['total']" v-model:page="formInline.pageNum" v-model:limit="formInline.pageSize" @pagination="getInfo" />

    <approval ref="approvalCom" @fatherMethods="search" request="workCaseAudit"></approval>

    <el-dialog v-model="dialogVisible" title="新增订单" width="800" :before-close="handleClose">
      <el-form :model="form" label-width="100" :rules="rules" ref="formEl">
        <el-form-item label="工种类型" prop="workTypeId">
          <workTypeSelect v-model="form.workTypeId"></workTypeSelect>
        </el-form-item>
        <el-form-item label="工作地点" prop="areaCode">
          <el-input v-model="form.address" placeholder="请输入工作地点" class="selectInput">
            <template #prepend>
              <areaSelect v-model="form.areaCode"></areaSelect>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="内容描述" prop="requirement">
          <el-input v-model="form.requirement" placeholder="请输入内容描述" type="textarea" :autosize="{ minRows : 4 }" />
        </el-form-item>
        <el-form-item label="价格" prop="oneDayWage">
          <el-input-number v-model="form.oneDayWage" :min="1" />
        </el-form-item>
        <el-form-item label="联系人" prop="userId">
          <userSelect v-model="form.userId"></userSelect>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <!-- <el-form-item label="用工人数" prop="workNum">
          <dictCode dict="work_num" v-model="form.workNum"></dictCode>
        </el-form-item>
        <el-form-item label="预计工期" prop="constructionPeriod">
          <dictCode dict="construction_period" v-model="form.constructionPeriod"></dictCode>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="visible" title="指派订单" width="500" :before-close="handleClose">
      <el-form :model="params" label-width="100">
        <el-form-item label="指派人搜索">
          <userSelect v-model="params.appUserId"></userSelect>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submit" :loading="assignLoading">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="open" title="详情" width="500" :before-close="handleClose">
      <span style="white-space: pre-wrap">{{row.requirement?row.requirement:row.title}}</span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import approval from "@/views/freeLobbyManage/components/approval.vue"; //审批
import { onMounted } from "vue";

const { proxy } = getCurrentInstance();

let assignLoading = ref(false);
let open = ref(false);
let formInline = ref({
  workTypeId: "",
  startTime: "",
  endTime: "",
  status: "",
  pageNum: 1,
  pageSize: 10,
});
let params = ref({
  appUserId: "",
  id: "",
  userId: "",
});
let tableData = ref({});
let visible = ref(false);
let auditStateList = ref([
  { name: "待指派", value: 0 },
  { name: "待接单", value: 1 },
  { name: "已拒单", value: 2 },
  { name: "已接单", value: 3 },
  { name: "已完成", value: 4 },
  { name: "待评价", value: 5 },
]);
let form = ref({
  workTypeId: "",
  oneDayWage: null,
  phone: null,
  address: "",
  title: "",
  workNum: null,
  constructionPeriod: null,
  userId: null,
  areaCode: "",
  requirement: "",
});
//验证手机号
const validateMobile = async (rule: any, value: any, callback: any) => {
  if (value) {
    if (proxy.$utils.isPoneAvailable(value)) {
      callback();
    } else {
      callback(new Error("请输入正确的手机号"));
    }
  } else {
    callback();
  }
};
const rules = reactive<FormRules<RuleForm>>({
  requirement: [{ required: true, message: "请输入招工需求", trigger: "blur" }],
  workTypeId: [{ required: true, message: "请选择工种类型", trigger: "blur" }],
  areaCode: [{ required: true, message: "请选择省市区", trigger: "blur" }],
  phone: [{ required: true, validator: validateMobile, trigger: "blur" }],
  userId: [{ required: true, message: "请选择联系人", trigger: "blur" }],
  constructionPeriod: [
    { required: true, message: "请选择预计工期", trigger: "blur" },
  ],
  workNum: [{ required: true, message: "请选择用工人数", trigger: "blur" }],
});
let dialogVisible = ref(false);
let info = ref({});
let loading = ref(false);
let ids = ref([]);
let row = ref({});

onMounted(() => {
  search();
});

let disabledStatus = (e) => {
  return [1, 3, 4, 5].includes(e);
};

let tag_type = (e) => {
  switch (e) {
    case 2:
      return "danger";
      break;
    case 3:
      return "warning";
      break;
    case 4:
      return "success";
      break;
    case 5:
      return "info";
      break;
    default:
      break;
  }
};
let seeDetail = (e) => {
  row.value = { ...e };
  open.value = true;
};
const handleSelectionChange = (val: User[]) => {
  let arr = [];
  for (let index = 0; index < val.length; index++) {
    const element = val[index];
    arr.push(element.id);
  }
  ids.value = [...arr];
};
let search = () => {
  formInline.value.pageNum = 1;
  getInfo();
};
let getInfo = async () => {
  tableData.value = await proxy.$apis.platformOrderPage(formInline.value);
};
let init = () => {
  formInline.value = {
    workTypeId: "",
    startTime: "",
    endTime: "",
    status: "",
    pageNum: 1,
    pageSize: 10,
  };
  getInfo();
};
let auditState_format = (e) => {
  for (let index = 0; index < auditStateList.value.length; index++) {
    const element = auditStateList.value[index];
    if (element.value == e) return element.name;
  }
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!proxy.$refs.formEl) return;
  await proxy.$refs.formEl.validate((valid, fields) => {
    if (valid) {
      save();
    } else {
      console.log("error submit!", fields);
    }
  });
};
let save = async () => {
  try {
    loading.value = true;
    await proxy.$apis.platformOrderAdd(form.value);
    proxy.$utils.showToast("新增成功");
    handleClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
let handleClose = () => {
  params.value = {
    appUserId: "",
    id: "",
    userId: "",
  };
  form.value = {
    workTypeId: "",
    oneDayWage: null,
    phone: null,
    address: "",
    title: "",
    workNum: null,
    constructionPeriod: null,
    userId: null,
    areaCode: "",
    requirement: "",
  };
  if (proxy.$refs.formEl) proxy.$refs.formEl.resetFields();
  getInfo();
  dialogVisible.value = false;
  visible.value = false;
  open.value = false;
};
let handleClick = async (row, num) => {
  switch (num) {
    case 1:
      params.value.id = row.id;
      params.value.userId = row.userId;
      visible.value = true;
      break;
    case 2:
      ids.value = [row.id];
      orderDel();
      break;
    default:
      break;
  }
};
let orderDel = async () => {
  let resp = await proxy.$utils.confirmTips("是否确定删除?");
  if (!resp) return;
  await proxy.$apis.platformOrderDel({ ids: ids.value });
  proxy.$utils.showToast("删除成功");
  getInfo();
};
let submit = async () => {
  try {
    if (!params.value.appUserId)
      return proxy.$utils.showToast("请先选择指派用户", 0);
    assignLoading.value = true;
    if (params.value.userId == params.value.appUserId)
      return proxy.$utils.showToast("订单不能指派给自己", 0);
    let query = { ...params.value };
    delete query.userId;
    await proxy.$apis.assignOrder(query);
    proxy.$utils.showToast("指派成功");
    handleClose();
  } catch (error) {
  } finally {
    assignLoading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.content {
  margin: 20px;
}
</style>
